/**
 * File FileReceiverHandler.java 
 */
package cs.ni;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
//import java.nio.file.Files;
import java.util.Observable;

import cs.entity.User;
import cs.entity.UserFile;

/**
 * Manages receiving a file via a thread. <p>
 * Package  cs.ni
 * Project ChatSystemG1 - INSA 4INFOA1 - 2013/2014
 * @author Julie DUMONS & Juste OUEDRAOGO
 */
public class FileReceiverHandler extends Observable implements Runnable{
	/**
	 * socket for file download
	 */
	private Socket socket;

	/**
	 * Constructor
	 * @param sock the TCP socket used for this communication
	 */
	public FileReceiverHandler(Socket sock){
		socket = sock;

	}
	@Override
	public void run() {
		InputStream is = null;
		FileOutputStream fos = null;
		BufferedInputStream bos = null;
		int bufferSize = 0;
		try {

			is = socket.getInputStream();
			bufferSize = socket.getReceiveBufferSize();
			bos = new BufferedInputStream(socket.getInputStream());

			//temporary file
			String filename = "downloaded"+socket.getInetAddress().getHostAddress();
			FileOutputStream out = new FileOutputStream(filename);
			int count = 0;
			byte[] buffer = new byte[bufferSize];
			while ((count = bos.read(buffer)) > 0)
			{
				out.write(buffer, 0, count);
			}
			out.close();
			bos.close();
			is.close();

			UserFile received = new UserFile(new User(null, socket.getInetAddress()), new File(filename));
			setChanged();
			received.setState(UserFile.State.COMPLETED);
			notifyObservers(received);
		} catch (IOException ex) {
			System.out.println("Can't get socket input stream. ");
			UserFile received = new UserFile(new User(null, socket.getInetAddress()), new File(""));
			setChanged();
			received.setState(UserFile.State.FAILED);
			notifyObservers(received);
		}

	}
}
